<template>
  <el-row>
    <!-- <h4>关联资源</h4> -->

    <div class="all">
      <div class="left">
        <div class="top">
          <div class="top_l">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          </div>
          <div class="top_r">
            <el-button type="primary" @click="update">保存</el-button>
          </div>
        </div>
        <div class="botton">
          <el-tree
            class="filter-tree"
            check-strictly
            :node-key="getTreeNodeKey"
            :data="treeData"
            show-checkbox
            node-key="id"
            highlight-current
            :props="defaultProps"
            :filter-node-method="filterNode"
            ref="menuTree"
            @node-click="getNodeData"
            default-expand-all
          ></el-tree>
        </div>
      </div>
      <div class="right">
        <el-button type="primary" @click="savesql('保存小方块')">保存</el-button>
        <el-checkbox-group v-model="checkList">
          <!-- <el-checkbox class="linb" label="复选框 A"></el-checkbox>
          <el-checkbox class="linb" label="复选框 B"></el-checkbox>
          <el-checkbox class="linb" label="复选框 C"></el-checkbox>
          <el-checkbox class="linb" label="禁用"></el-checkbox>
          <el-checkbox class="linb" label="选中且禁用"></el-checkbox>-->
          <el-checkbox
            class="linb"
            v-for="(item,index) in allquer"
            :label="item"
            :key="item.id*index"
          >{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
  </el-row>
</template>
<script>
import { fetchTree } from "api/admin/menu/index";
import { page } from "api/admin/element/index";
import {
  removeElementAuthority,
  addElementAuthority,
  getElementAuthority,
  modifyMenuAuthority,
  getMenuAuthority
} from "api/admin/group/index";
import {
  findByUserId,
  flLittlebutton,
  ugridPdate,
  flSwitchforla,
  flGroupBtttonAddAll,
  getSFlLittlebutton
} from "api/login";
import { mapGetters } from "vuex";

//获取SysCompanyCode
import { forSysCompanyCode } from "api/new20191221/institutionalFramework";
export default {
  name: "menu",
  props: {
    groupId: {
      default: "1"
    }
  },
  data() {
    return {
      filterText: "",
      list: null,
      total: null,
      listQuery: {
        name: undefined
      },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "title"
      },
      groupManager_menu: false,
      groupManager_element: false,
      //   currentId: -1

      newSysCompanyCode: 0,
      //所有小方快
      allquer: [],
      //多选
      checkList: [
        // "选中且禁用", "复选框 A"
      ]
    };
  },
  watch: {
    filterText(val) {
      this.$refs.menuTree.filter(val);
    }
  },
  async created() {
    let token = this.$store.state.user.token;
    await forSysCompanyCode(token)
      .then(response => {
        this.newSysCompanyCode = response.sysCompanyCode;
      })
      .catch(error => {
        alert("获取forSysCompanyCode失败！");
      });
    this.getList();
    this.groupManager_menu = this.elements["groupManager:menu"];
    this.groupManager_element = this.elements["groupManager:element"];
    //获取所有小方块
    flLittlebutton().then(response => {
      this.allquer = response.data;
      console.log(this.allquer);
    });
  },
  computed: {
    ...mapGetters(["elements"])
  },
  methods: {
    getList() {
      let token = this.$store.state.user.token;
      this.listQuery["token"] = token;
      this.listQuery["sysCompanyCode"] = this.newSysCompanyCode;
      console.log(this.listQuery);
      fetchTree(this.listQuery).then(data => {
        this.treeData = data;
        this.initAuthoritys();
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getNodeData(data) {
      this.listQuery.menuId = data.id;
      page(this.listQuery).then(response => {
        this.list = response.data.rows;
        getElementAuthority(this.groupId).then(data => {
          const obj = {};
          for (let i = 0; i < this.list.length; i++) {
            obj[this.list[i].id] = this.list[i];
          }
          const toggle = {};
          for (let i = 0; i < data.data.length; i++) {
            const id = data.data[i];
            if (obj[id] !== undefined && toggle[id] === undefined) {
              this.$refs.elementTable.toggleRowSelection(obj[data.data[i]]);
              toggle[id] = true;
            }
          }
        });
      });
      this.currentId = data.id;
      this.showElement = true;

      //获取选中的小方块
      getSFlLittlebutton(this.currentId).then(response => {
        console.log(response);
        let selArr = []; //选中的name集合
        for (let i = 0; i < this.allquer.length; i++) {
          for (let j = 0; j < response.data.length; j++) {
            if (this.allquer[i].name == response.data[j].name) {
              // console.log(response.data[j].name)
              selArr.push(response.data[j].name);
            }
          }
        }
        let newSelArr = [...new Set(selArr)];
        // console.log(newSelArr)
        let overArr = [];
        for (let x = 0; x < newSelArr.length; x++) {
          for (let y = 0; y < this.allquer.length; y++) {
            if (newSelArr[x] == this.allquer[y].name) {
              let obj = new Object();
              obj = this.allquer[y];
              overArr.push(obj);
            }
          }
        }
        console.log(overArr);
        this.checkList = overArr;
      });
    },
    //保存小方块
    savesql() {
      //groupId
      let groupId = this.currentId;
      let obj = this.checkList;
      console.log(obj);
      flGroupBtttonAddAll(groupId, obj)
        .then(response => {
          console.log(response);
          this.$message({
            message: "保存成功！",
            type: "success"
          });
        })
        .catch(() => {
          this.$message.error("保存失败！");
        });
    },
    getTreeNodeKey(node) {
      return node.id;
    },
    handleSelectionChange(val, row) {
      let flag = true;
      for (let i = 0; i < val.length; i++) {
        if (val[i].id === row.id) {
          addElementAuthority(this.groupId, {
            menuId: this.currentId,
            elementId: row.id
          });
          flag = false;
          break;
        }
      }
      if (flag) {
        removeElementAuthority(this.groupId, {
          menuId: this.currentId,
          elementId: row.id
        });
      }
    },
    update() {
      this.$emit("closeAuthorityDialog");
      const nodes = this.$refs.menuTree.getCheckedNodes();
      const ids = [];
      for (let i = 0; i < nodes.length; i++) {
        ids.push(nodes[i].id);
      }
      modifyMenuAuthority(this.groupId, {
        menuTrees: ids.join()
      }).then(() => {
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
          duration: 2000
        });
      });
    },
    initAuthoritys() {
      getMenuAuthority(this.groupId).then(data => {
        const result = [];
        for (let i = 0; i < data.data.length; i++) {
          result.push(data.data[i].id);
        }
        this.$refs.menuTree.setCheckedKeys(result);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.all {
  display: flex;
  .left {
    width: 300px;
    height: 450px;
    overflow: auto;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      height: 50px;
      .top_l {
        flex: 1;
      }
      .top_r {
        width: 75;
      }
    }
    .botton {
      flex: 1;
    }
  }
  .right {
    flex: 1;
    border-left: 1px solid #ccc;
    .linb {
      display: block;
      margin: 10px;
    }
  }
}
</style>
